from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required
from . import network
from .. import db
from ..models import PipeNetwork, MaintenanceRecord
from datetime import datetime

@network.route('/network')
@login_required
def network_index():
    # 获取查询参数
    search_name = request.args.get('name', '')
    search_type = request.args.get('pipe_type', '')
    search_status = request.args.get('status', '')
    
    # 构建查询条件
    query = PipeNetwork.query
    if search_name:
        query = query.filter(PipeNetwork.name.like(f'%{search_name}%'))
    if search_type:
        query = query.filter(PipeNetwork.pipe_type == search_type)
    if search_status:
        query = query.filter(PipeNetwork.status == search_status)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(PipeNetwork.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    pipes = pagination.items
    
    return render_template('network/index.html',
                         pipes=pipes,
                         pagination=pagination,
                         search_name=search_name,
                         search_type=search_type,
                         search_status=search_status,
                         title='管网管理')

@network.route('/network/add', methods=['GET', 'POST'])
@login_required
def network_add():
    if request.method == 'POST':
        pipe = PipeNetwork(
            name=request.form.get('name'),
            pipe_type=request.form.get('pipe_type'),
            material=request.form.get('material'),
            diameter=float(request.form.get('diameter')),
            length=float(request.form.get('length')),
            start_point=request.form.get('start_point'),
            end_point=request.form.get('end_point'),
            installation_date=datetime.strptime(request.form.get('installation_date'), '%Y-%m-%d').date(),
            status=request.form.get('status'),
            description=request.form.get('description')
        )
        
        db.session.add(pipe)
        db.session.commit()
        flash('管网添加成功', 'success')
        return redirect(url_for('network.network_index'))
    
    return render_template('network/add.html', title='添加管网')

@network.route('/network/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def network_edit(id):
    pipe = PipeNetwork.query.get_or_404(id)
    
    if request.method == 'POST':
        pipe.name = request.form.get('name')
        pipe.pipe_type = request.form.get('pipe_type')
        pipe.material = request.form.get('material')
        pipe.diameter = float(request.form.get('diameter'))
        pipe.length = float(request.form.get('length'))
        pipe.start_point = request.form.get('start_point')
        pipe.end_point = request.form.get('end_point')
        pipe.installation_date = datetime.strptime(request.form.get('installation_date'), '%Y-%m-%d').date()
        pipe.status = request.form.get('status')
        pipe.description = request.form.get('description')
        
        db.session.commit()
        flash('管网信息更新成功', 'success')
        return redirect(url_for('network.network_index'))
    
    return render_template('network/edit.html',
                         pipe=pipe,
                         title='编辑管网')

@network.route('/network/maintenance/<int:pipe_id>', methods=['GET', 'POST'])
@login_required
def maintenance_add(pipe_id):
    pipe = PipeNetwork.query.get_or_404(pipe_id)
    
    if request.method == 'POST':
        record = MaintenanceRecord(
            pipe_id=pipe_id,
            maintenance_type=request.form.get('maintenance_type'),
            maintenance_date=datetime.strptime(request.form.get('maintenance_date'), '%Y-%m-%dT%H:%M'),
            description=request.form.get('description'),
            operator=request.form.get('operator'),
            status=request.form.get('status')
        )
        
        db.session.add(record)
        db.session.commit()
        flash('维护记录添加成功', 'success')
        return redirect(url_for('network.maintenance_history', pipe_id=pipe_id))
    
    return render_template('network/maintenance_add.html',
                         pipe=pipe,
                         title='添加维护记录')

@network.route('/network/maintenance/history/<int:pipe_id>')
@login_required
def maintenance_history(pipe_id):
    pipe = PipeNetwork.query.get_or_404(pipe_id)
    
    # 获取搜索参数
    search_type = request.args.get('maintenance_type', '')
    search_status = request.args.get('status', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    
    # 构建查询
    query = MaintenanceRecord.query.filter_by(pipe_id=pipe_id)
    
    if search_type:
        query = query.filter(MaintenanceRecord.maintenance_type == search_type)
    if search_status:
        query = query.filter(MaintenanceRecord.status == search_status)
    if start_date:
        query = query.filter(MaintenanceRecord.maintenance_date >= datetime.strptime(start_date, '%Y-%m-%d'))
    if end_date:
        # 将结束日期设置为当天的最后一刻
        end_datetime = datetime.strptime(end_date, '%Y-%m-%d').replace(hour=23, minute=59, second=59)
        query = query.filter(MaintenanceRecord.maintenance_date <= end_datetime)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(MaintenanceRecord.maintenance_date.desc()).paginate(
        page=page, per_page=10, error_out=False)
    records = pagination.items
    
    return render_template('network/maintenance_history.html',
                         pipe=pipe,
                         records=records,
                         pagination=pagination,
                         search_type=search_type,
                         search_status=search_status,
                         start_date=start_date,
                         end_date=end_date,
                         title='维护记录') 